package com.talent.service.iot.mqtt.handler;

import com.talent.service.iot.mqtt.config.Constant;
import com.talent.service.iot.mqtt.model.entity.TlTopic;
import com.talent.service.iot.mqtt.model.payload.TlMqttUnSubscribePayload;
import com.talent.service.iot.mqtt.model.request.TlMqttUnSubscribeReq;
import com.talent.service.iot.mqtt.model.response.TlMqttUnSubAck;
import com.talent.service.iot.mqtt.service.IMqttSubscriptionService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName：ConnectHandler
 * @Author: hszhou
 * @Date: 2024/11/25 11:06
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@ChannelHandler.Sharable
@Component
public class TlMqttUnSubScribeHandler extends SimpleChannelInboundHandler<TlMqttUnSubscribeReq> {

    private static final  Logger logger = LoggerFactory.getLogger(TlMqttUnSubScribeHandler.class);


    private  final IMqttSubscriptionService subscriptionService;


    public TlMqttUnSubScribeHandler(IMqttSubscriptionService subscriptionService){
        this.subscriptionService = subscriptionService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TlMqttUnSubscribeReq msg) throws Exception {
        String clientId = ctx.channel().attr(AttributeKey.valueOf(Constant.CLIENT_ID)).get().toString();
        TlMqttUnSubscribePayload payload = msg.getPayload();
        List<TlTopic> topics = payload.getTopics();
        //取消订阅 就移除掉主题对应的客户端 这样发送消息就接收不到
        for (TlTopic topic : topics) {
            logger.debug("client 【{}】 unsubscribe topic 【{}】",clientId,topic.getName());
            subscriptionService.unsubscribe(clientId,topic.getName()).subscribe();
        }

        //构建ack消息
        int messageId = msg.getVariableHead().getMessageId();
        TlMqttUnSubAck res = TlMqttUnSubAck.of(messageId);
        ctx.channel().writeAndFlush(res);
        logger.debug("【UNSUBSCRIBE】 messageId =【{}】",messageId);

    }
}
